﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;


namespace Hybrid.Threading.Sync
{
    class SynchronizedQueue<T>
    {
        private readonly object m_lock = new object();
        private readonly Queue<T> m_queue = new Queue<T>();

        public void Qnqueue(T item)//入队
        {
            Monitor.Enter(m_lock);
            m_queue.Enqueue(item);//一个数据项入队后,就唤醒任何正在等待的线程
            Monitor.PulseAll(m_lock);
            Monitor.Exit(m_lock);
        }

        public T Dequeue()//出队
        {
            Monitor.Enter(m_lock);
            while (m_queue.Count == 0)//队列为空(这是条件)就一直循环
            {
                Monitor.Wait(m_queue);
            }

            T item = m_queue.Dequeue();//使一个数据项出队,返回它供处理
            Monitor.Exit(m_lock);
            return item;
        }
    }
}
